


/*
state之间通知
 */


import 'package:xsdk_flutter/xsdk/utils/x_utils_log.dart';

typedef XFunctionNotifyStateChangeListener<T> = void Function(String key,dynamic value);

abstract class XNotifyStateChangeUtils{


  static final Map<String,List<XFunctionNotifyStateChangeListener>?> _map={};

  //注册
  static void receiveChangeNotify(
      {
        required String action,
        required XFunctionNotifyStateChangeListener listener,
        bool isReplaceThisActionAllListener=false,
      }
      ){

    List<XFunctionNotifyStateChangeListener>? list=_map[action];
    if(list==null){
      //XLogUtils.printLog('---receiveChangeNotify,list==null');
      list = [];
      list.add(listener);
      _map[action]=list;
    }else{
      if(isReplaceThisActionAllListener){
        list.clear();
      }
      list.add(listener);
      //XLogUtils.printLog('---receiveChangeNotify,list!=null,length=${list.length}');
    }

  }

  /*
  清除监听
  listener: 指定listener清除,如在当前page的onDestory中销毁指定的listener
  注意: 当listener=null时,机制:新page先创建,后销毁旧的page,当新page中存在相同的action时,会被销毁监听;
   */
  static void unReceiveChangeNotify(
      {
        required String action,
        required XFunctionNotifyStateChangeListener? listener,
      }
      ){
    //
    if(listener==null){
      _map.remove(action);
    }else{
      List<XFunctionNotifyStateChangeListener>? list=_map[action];
      if(list!=null){
        list.remove(listener);
      }
    }
  }

  //发送
  static void notifyStateChange({
    required String action,
    required String key,
    required dynamic value
  }){

    try{

      List<XFunctionNotifyStateChangeListener>? list=_map[action];
      if(list!=null){
        for(XFunctionNotifyStateChangeListener listener in list){
          listener(key,value);
        }
      }

    }catch(e){
      //
    }
  }


}